import fs from 'fs';
import path from 'path';
import prettier from 'prettier';
import utils from './utils';
import { isDocFile, compileDocStyle } from './compile-doc-style';
import pkg from '../package.json';

const env = process.env.ENV;
const { log, mkdir, rmdir, grab, exist, resolve, minifyJSON, isJunk } = utils;
const { title } = pkg.project.common;
const baseURL = pkg.project.env[env] ? pkg.project.env[env]['baseURL'] : 'dev';
const docScssPlugin = (env) => ({
    name: 'generate-doc-css',
    configResolved(config) {
        compileDocStyle(env);
    },
    handleHotUpdate({ server, file, module }) {
        if (isDocFile(file)) {
            compileDocStyle(env);

            const reload = () => {
                server.ws.send(
                    {
                        type: 'full-reload',
                    },
                    100
                );
            };

            if (!isJunk(file)) {
                reload();
            }
        }
    },
});

const htmlPlugin = () => ({
    name: 'index-html-transform',
    transformIndexHtml(code) {
        let result = code;
        result = result.replace(
            /<title>(.*?)<\/title>/gi,
            `<title>${title}</title>`
        );

        result = prettier.format(result, {
            tabWidth: 4,
            useTabs: true,
            parser: 'html',
        });

        return result;
    },
});

const removePlugin = () => ({
    name: 'code-transform',
    transform(code, id) {
        let result = code;
        // <remove> </remove>
        if (/\.(js|vue|jsx|ts|tsx)$/.test(id)) {
            result = result.replace(
                /(\/\/\s*\<remove\>\s*(\n|\r|.)*?\/\/\s*\<\/remove\>)/gi,
                (a, b) => {
                    return '';
                }
            );
        }
        return result;
    },
});

const endPlugin = () => ({
    name: 'end-close-bundle',
    closeBundle() {
        const jsonDataDir = resolve('./src/assets/json/');
        if (!fs.existsSync(jsonDataDir)) {
            return;
        }
        grab(jsonDataDir, '.json', (err, results) => {
            if (err) throw err;

            // clean previous folder
            rmdir(
                [resolve('./dist/assets/json/')],
                () => {
                    const sourceFiles = results;
                    for (let i = 0; i < sourceFiles.length; i++) {
                        const file = sourceFiles[i];
                        let source = fs.readFileSync(file, 'utf-8');
                        source = minifyJSON(source);

                        // filter out fileName to get parent's folderName
                        const distFile =
                            'dist/assets/json/' + path.basename(file);
                        const arr = distFile.split('/');
                        const distFolder = arr
                            .splice(0, arr.length - 1)
                            .join('/');

                        if (!exist(distFolder)) {
                            mkdir(distFolder);
                        }
                        fs.writeFileSync(resolve(distFile), source, 'utf-8');
                    }
                },
                false
            );
        });
    },
});

export { docScssPlugin, removePlugin, htmlPlugin, endPlugin };
